package com.hdphone.zljutils.impl;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;

import androidx.annotation.NonNull;

import com.hdphone.zljutils.ZljUtils;
import com.hdphone.zljutils.inter.IStringUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @date: 2021/6/3
 * @email： yzandlj@163.com
 * @author： yangzhi
 * @describe:
 */
public class StringUtilImpl implements IStringUtil {
    private static final String TAG = "StringUtils";

    /**
     * 生成oid的最后随机数的长度
     */
    private static final int OID_RANDOM_LENGTH = 5;

    @Override
    public String getMobilePhone(String phone) {
        if (phone.length() >= 7) {
            String a = phone.substring(0, 3);
            String b = phone.substring(phone.length() - 4, phone.length());
            return a + "****" + b;
        }
        return "";
    }

    /**
     * 从URL中获取比例
     */
    @Override
    public float getProportionFromUrl(String url, float defaultProportion) {
        float aspectRatio = defaultProportion;
        if (!TextUtils.isEmpty(url)) {
            Map<String, String> stringMap = urlSplitIgnoreCase(url);
            if (stringMap.containsKey("proportion")) {
                String proportion = stringMap.get("proportion");
                if (!TextUtils.isEmpty(proportion) && stringToFloat(proportion) > 0) {
                    aspectRatio = stringToFloat(proportion);
                }
            }
        }
        ZljUtils.LOG().d(TAG, "getProportionFromUrl -- > " + aspectRatio);
        return aspectRatio;
    }

    /**
     * URLget请求参数拼接
     *
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public String createLinkStringByGet(Map<String, String> params) throws UnsupportedEncodingException {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (key == null || value == null)
                continue;
            value = URLEncoder.encode(value, "UTF-8");
            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    /**
     * 解析出url参数中的键值对,全部换为小写
     *
     * @param url url地址
     * @return url请求参数部分(url中的参数转化为map集合中key都为小写)
     */
    @Override
    public Map<String, String> urlSplit(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        if (TextUtils.isEmpty(url)) {
            return mapRequest;
        }
        try {
            String[] arrSplit = null;
            String strUrlParam = truncateUrlPage(url);//转为小写
            if (strUrlParam == null) {
                return mapRequest;
            }
            arrSplit = strUrlParam.split("[&]");
            for (String strSplit : arrSplit) {
                String[] arrSplitEqual = null;
                arrSplitEqual = strSplit.split("[=]");
                //解析出键值
                if (arrSplitEqual.length > 1) {
                    //正确解析
                    mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
                } else {
                    if (arrSplitEqual[0] != "") {
                        //只有参数没有值，不加入
                        mapRequest.put(arrSplitEqual[0], "");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mapRequest;
    }

    /**
     * 解析出url参数中的键值对,不改变大小写
     *
     * @param url url地址
     * @return url请求参数部分
     */
    @Override
    public Map<String, String> urlSplitIgnoreCase(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        if (TextUtils.isEmpty(url)) {
            return mapRequest;
        }
        try {
            String[] arrSplit = null;
            String strUrlParam = truncateUrlPageIgnoreCase(url);
            if (strUrlParam == null) {
                return mapRequest;
            }
            arrSplit = strUrlParam.split("[&]");
            for (String strSplit : arrSplit) {
                String[] arrSplitEqual = null;
                arrSplitEqual = strSplit.split("[=]");
                //解析出键值
                if (arrSplitEqual.length > 1) {
                    //正确解析
                    mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
                } else {
                    if (arrSplitEqual[0] != "") {
                        //只有参数没有值，不加入
                        mapRequest.put(arrSplitEqual[0], "");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapRequest;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     * 注意url全部转化为小写
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private String truncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;
        strURL = strURL.trim().toLowerCase();//转为小写
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 去掉url中的路径，留下请求参数部分 ,不改变大小写
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private String truncateUrlPageIgnoreCase(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;
        strURL = strURL.trim();
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 是否为null或空字符串
     *
     * @param str 字符串
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        }
        return false;
    }

    /**
     * 包含 null 字符串的为空判断
     *
     * @param str 字符串
     * @return boolean
     */
    @Override
    public boolean isNEmpty(String str) {
        return isEmpty(str) || (isNotEmpty(str) && "null".equals(str.trim().toLowerCase()));
    }

    @Override
    public boolean isNEmpty(String str1, String str2) {
        if (isEmpty(str1) && isEmpty(str2))
            return true;
        return false;
    }

    /**
     * 非null或非空
     *
     * @param str 字符串
     * @return boolean
     */
    @Override
    public boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 用于判断输入框输入是否是中文
     *
     * @param str 字符串
     * @return boolean
     */
    @Override
    public boolean isCN(String str) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            if (bytes.length == str.length()) {
                return false;
            } else {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            ZljUtils.LOG().d(TAG, "StringUtil 中isCN() 方法报异常:" + e);
        }
        return false;
    }


    /**
     * <判断是否为身份证号码>
     *
     * @param IdCard 身份证号
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public boolean isIDCard(String IdCard) {
        String reg = "(\\d{15}[0-9Xx])|(\\d{17}[0-9Xx])";
        return IdCard.matches(reg);
    }

    /**
     * <判断是否是数字>
     *
     * @param str 字符串
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public boolean isNumber(String str) {
        String reg = "[0-9]+";
        return str.matches(reg);
    }


    /**
     * 是否是邮件
     *
     * @param str 字符串
     * @return boolean
     */
    @Override
    public boolean isEmail(String str) {
        Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 字符串转为整数(如果转换失败,则返回 -1)
     *
     * @param str 字符串
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public int stringToInt(String str) {
        if (isEmpty(str)) {
            return -1;
        }
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * 字符串转为整数(如果转换失败,则返回 defaultValue)
     *
     * @param str          字符串
     * @param defaultValue 默认值
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public int stringToInt(String str, int defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * <字符串转为long(如果转换失败,则返回 -1)> <功能详细描述>
     *
     * @param str 字符串转
     * @return long [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public long stringToLong(String str) {
        if (isEmpty(str)) {
            return -1;
        }
        try {
            return Long.parseLong(str.trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * <字符串转为long(如果转换失败,则返回 -1)> <功能详细描述>
     *
     * @param str 字符串转
     * @return long [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public long stringToLong(String str, long defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }
        try {
            return Long.parseLong(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * 字符串转为Float(如果转换失败,则返回 -1)
     *
     * @param str 字符串
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public float stringToFloat(String str) {
        if (isEmpty(str)) {
            return -1;
        }
        try {
            return Float.parseFloat(str.trim());
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * 字符串转为Float(如果转换失败,则返回 -1)
     *
     * @param str 字符串
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public float stringToFloat(String str, @NonNull float defaultNum) {
        if (isEmpty(str)) {
            return defaultNum;
        }
        try {
            return Float.parseFloat(str.trim());
        } catch (NumberFormatException e) {
            return defaultNum;
        }
    }

    /**
     * 字符串转为Double(如果转换失败,则返回 -1)
     *
     * @param str 字符串
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public double stringToDouble(String str) {
        return stringToDouble(str, -1);
    }

    /**
     * 字符串转为Double(如果转换失败,则返回 -1)
     *
     * @param str 字符串
     * @return int [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public double stringToDouble(String str, double defaultNum) {
        if (isEmpty(str)) {
            return defaultNum;
        }
        try {
            return Double.parseDouble(str.trim());
        } catch (NumberFormatException e) {
            return defaultNum;
        }
    }

    /**
     * 字体串转为boolean (如果转换失败,则返回false)
     *
     * @param str 字符串转
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public boolean stringToBoolean(String str) {
        if (isEmpty(str)) {
            return false;
        }
        try {
            return Boolean.parseBoolean(str.trim());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * boolean转为字体串
     *
     * @param bool boolean
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String booleanToString(Boolean bool) {
        String booleanString = "false";
        if (bool) {
            booleanString = "true";
        }
        return booleanString;
    }

    /**
     * <从异常中获取调用栈>
     *
     * @param ex Throwable
     * @return String [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String getExceptionStackTrace(Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        return writer.toString();
    }

    /**
     * <Unicode转化为中文>
     *
     * @param dataStr Unicod字体串
     * @return String [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String decodeUnicode(String dataStr) {
        final StringBuffer buffer = new StringBuffer();
        String tempStr = "";
        String operStr = dataStr;
        if (operStr != null && operStr.indexOf("\\u") == -1) {
            return buffer.append(operStr).toString();
        }
        if (operStr != null && !operStr.equals("") && !operStr.startsWith("\\u")) {
            tempStr = substring(operStr, 0, operStr.indexOf("\\u"));
            operStr = substring(operStr, operStr.indexOf("\\u"), operStr.length());
        }
        buffer.append(tempStr);
        // 循环处理,处理对象一定是以unicode编码字符打头的字符串
        while (operStr != null && !operStr.equals("") && operStr.startsWith("\\u")) {
            tempStr = substring(operStr, 0, 6);
            operStr = substring(operStr, 6, operStr.length());
            String charStr = "";
            charStr = substring(tempStr, 2, tempStr.length());
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串
            buffer.append(letter);
            if (operStr.indexOf("\\u") == -1) {
                buffer.append(operStr);
            } else { // 处理operStr使其打头字符为unicode字符
                tempStr = substring(operStr, 0, operStr.indexOf("\\u"));
                operStr = substring(operStr, operStr.indexOf("\\u"), operStr.length());
                buffer.append(tempStr);
            }
        }
        return buffer.toString();
    }

    /**
     * 字条串截取
     *
     * @param str   源字符串
     * @param start 开始位置
     * @param end   结束位置
     * @return String [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String substring(String str, int start, int end) {
        if (isEmpty(str)) {
            return "";
        }
        int len = str.length();
        if (start > end) {
            return "";
        }
        if (start > len) {
            return "";
        }
        if (end > len) {
            return str.substring(start, len);
        }
        return str.substring(start, end);
    }

    /**
     * 字条串截取
     *
     * @param str   源字符串
     * @param start 开始位置
     * @return String [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String substring(String str, int start) {
        if (isEmpty(str)) {
            return "";
        }
        int len = str.length();
        if (start > len) {
            return "";
        }
        return str.substring(start);
    }

    /**
     * <将字符串截取为较短的字符串>
     *
     * @param content 字符串
     * @param length  长度
     * @return CharSequence
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String cutString(String content, int length) {
        if (isEmpty(content)) {
            return "";
        }
        if (content.length() <= length) {
            return content;
        }
        return content.substring(0, length);
    }

    /**
     * <将字符串多空格，多换行替换成一个空格> <功能详细描述>
     *
     * @param content 字符串
     * @return String [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String tirmString(String content) {
        if (isEmpty(content)) {
            return "";
        }

        return content.replaceAll("[ \n\r\t]+", " ");
    }

    /**
     * 判断字符是否数字
     *
     * @param str 字符
     * @return 数字
     */
    @Override
    public boolean isDigital(String str) {
        return str.matches("(-)?\\d+");
    }

    /**
     * 判断字符是否带小数
     *
     * @param str 字符
     * @return boolean
     */
    @Override
    public boolean isDouble(String str) {
        if (isDigital(str)) {
            return true;
        }
        return str.matches("(-)?\\d+\\.\\d+");
    }

    /**
     * 判断是否存在自定特殊字符
     *
     * @param str 字符
     * @return boolean [返回类型说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public boolean isErrorCodeStr(String str) {
        // 正则表达匹配是否有特殊字符
        // Pattern p = Pattern.compile(Common.STR_CREATE_CLOUD_FILE_ERROR);
        // Matcher m = p.matcher(str);
        //
        // return m.find();

        // "\\", "/", ":", "*", "?", "\"", "<", ">", "|"
        boolean b1 = str.contains("\\") || str.contains("/") || str.contains(":");
        boolean b2 = str.contains("*") || str.contains("?") || str.contains("\"");
        boolean b3 = str.contains("*") || str.contains("?") || str.contains("\"");
        return b1 || b2 || b3;
    }

    /**
     * 返回x小数,如果小数部分不够两位则自动填充小数部分
     *
     * @param process 字符
     * @return [参数说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public String getProcess(String process) {
        // 空字符
        if (null == process || "".equals(process.trim())) {
            return "";
        }

        // 非整数或小数
        if (!(isDigital(process) || isDouble(process))) {
            return process;
        }

        int index = process.indexOf('.');

        // 无小数部分
        if (-1 == index) {
            return process + ".00";
        }

        // 整数部分
        String prefix = process.substring(0, index);

        // 小数部分
        String postfix = process.substring(index + 1);

        StringBuilder result = new StringBuilder();

        // 小数部分长度
        switch (postfix.length()) {
            // 无小数部分
            case 0:
                result.append(prefix).append(".00");
                break;
            // 只有一位小数
            case 1:
                result.append(prefix).append('.').append(postfix).append('0');
                break;
            // 两位小数
            case 2:
                result.append(prefix).append('.').append(postfix);
                break;
            // 三位或以上小数,需要进行四舍五入
            default:
                result.append(String.valueOf(Math.round(Double.parseDouble(prefix + postfix.substring(0, 3)) / 10))).insert(result.length() - 2, '.');
                break;
        }
        return result.toString();
    }

    /**
     * 字符串转数字
     *
     * @param str          字符串
     * @param defualtValue 自定义整型
     * @return 整型
     */
    @Override
    public int getInt(String str, int defualtValue) {
        return isDigital(str) ? Integer.parseInt(str) : defualtValue;
    }


    /**
     * 去掉url中多余的斜杠
     *
     * @param url 字符串
     * @return 去掉多余斜杠的字符串
     */
    @Override
    public String fixUrl(String url) {
        if (null == url) {
            return "";
        }
        StringBuffer stringBuffer = new StringBuffer(url);
        for (int i = stringBuffer.indexOf("//", stringBuffer.indexOf("//") + 2); i != -1; i = stringBuffer.indexOf("//", i + 1)) {
            stringBuffer.deleteCharAt(i);
        }
        return stringBuffer.toString();
    }

    /**
     * 替换字符串中特殊字符
     *
     * @param strData 源字符串
     * @return 替换了特殊字符后的字符串，如果strData为NULL，则返回空字符串
     */
    @Override
    public String encodeString(String strData) {
        if (strData == null) {
            return "";
        }
        return strData.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("'", "&apos;").replaceAll("\"", "&quot;");
    }

    /**
     * 获取记录唯一ID
     *
     * @return String
     */
    @Override
    public String getOID() {
        return System.currentTimeMillis() + getRandomNum(OID_RANDOM_LENGTH);
    }

    /**
     * 返回特定长度的随机数
     *
     * @param length 返回长度
     * @return
     */
    private String getRandomNum(int length) {
        length = (length > 0) ? length : 10;
        StringBuffer sRand = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sRand.append((int) (Math.random() * 10));
        }
        return sRand.toString();
    }

    /**
     * 获取指定编码字符串的长度
     *
     * @param str      字符串
     * @param encoding 编码
     * @return int
     */
    @Override
    public int getStringLength(String str, String encoding) {
        if (isEmpty(str)) {
            return 0;
        }
        try {
            return str.getBytes(encoding).length;
        } catch (UnsupportedEncodingException e) {
            ZljUtils.LOG().e(TAG, "获取字符串长度时异常!", e);
            return -1;
        }
    }

    /**
     * 判断相同
     *
     * @param str0 字符串
     * @param str1 字符串
     * @return boolean
     */
    @Override
    public boolean areStringEqual(String str0, String str1) {
        // if(str0!=null){
        // return str0.equals(str1);
        // }
        // return str1==null || str1.length()==0;

        if (str0 == null || str0.length() == 0) {
            return str1 == null || str1.length() == 0;
        } else {
            return str0.equals(str1);
        }
    }

    /**
     * 隐藏字符串中间过长的部分
     *
     * @param src       原字符串
     * @param maxLength 最大长度
     * @param endLength 结尾长度
     * @return 隐藏后的字符串
     */
    @Override
    public String hideMiddleString(String src, int maxLength, int endLength) {
        if (src == null) {
            ZljUtils.LOG().w(TAG, "getMiddleString, src is null");
            return null;
        }

        String ellipsis = "...";
        if (maxLength <= endLength + ellipsis.length()) {
            return src;
        }
        if (src.length() <= maxLength) {
            return src;
        }

        // 截取后半段
        String endStr = src.substring(src.length() - endLength);

        // 截取前半段
        String startStr = src.substring(0, maxLength - endLength - ellipsis.length());
        return startStr + ellipsis + endStr;
    }

    /***
     * 字符串的长度是否某个区间
     *
     * @param str
     *            字符串
     * @param minLength
     *            最小长度
     * @param maxLength
     *            最大长度
     * @return boolean
     */
    @Override
    public boolean isStringLengthOk(String str, int minLength, int maxLength) {
        if (!isEmpty(str)) {
            int length = str.length();
            if (length >= minLength && length <= maxLength) {
                return true;
            }
        }
        return false;
    }

    /**
     * 转换百分比(统一保留小数点后两位数)
     *
     * @param num
     * @return
     */
    @Override
    public String getPercent(double num) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        return nf.format(num);
    }

    /**
     * 转换百分比(统一保留小数点后sacle位数)
     *
     * @param num
     * @return
     */
    @Override
    public String getPercent(double num, int sacle) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(sacle);
        return nf.format(num);
    }

    /**
     * 显示统一格式的数字(统一保留小数点后两位数)
     *
     * @param num
     * @return
     */
    @Override
    public String getDefaultNumber(double num) {
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.DOWN); // 向下取舍
        return df.format(num);
    }

    /**
     * 显示统一格式的数字(统一保留小数点后两位数)
     *
     * @param num
     * @return
     */
    @Override
    public String getDefaultNumber(String num) {
        String result = "";
        try {
            Double n = Double.parseDouble(num);
            result = getDefaultNumber(n);
        } catch (Exception e) {
            result = num;
        }
        return result;
    }

    /**
     * 显示货币金额数字（固定小数点后显示两位数字）
     *
     * @param num
     * @return
     */
    @Override
    public String getCashNumber(double num) {
        //DecimalFormat df = new DecimalFormat("0,000.##");
        //DecimalFormat df = new DecimalFormat("0,000.00");
        DecimalFormat df = new DecimalFormat("#,##0.00");
        df.setRoundingMode(RoundingMode.DOWN); // 向下取舍
        return df.format(num);
    }

    /**
     * 显示货币金额数字（固定小数点后显示两位数字）
     *
     * @param num
     * @return
     */
    @Override
    public String getCashNumber(String num) {
        String result = "";
        try {
            Double n = Double.parseDouble(num);
            result = getCashNumber(n);
        } catch (Exception e) {
            result = num;
        }
        return result;
    }


    /**
     * 高亮显示字符串里的数字
     *
     * @param srcTxt
     * @param highlightColor
     * @return
     */
    @Override
    public SpannableStringBuilder highlightShowNumFormText(String srcTxt, int highlightColor) {
        SpannableStringBuilder spannable = null;
        if (isNotEmpty(srcTxt)) {
            spannable = new SpannableStringBuilder(srcTxt);
            Pattern p = Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])");
            Matcher m = p.matcher(spannable);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                ZljUtils.LOG().d(TAG, "getHighlightText start = " + start + " end = " + end);
                spannable.setSpan(new ForegroundColorSpan(highlightColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannable;
    }

    /**
     * 改变小数点后面数字的大小
     *
     * @param value
     * @param proportion
     * @return
     */
    @Override
    public SpannableString changDecimalTVsize(String value, float proportion) {
        if (TextUtils.isEmpty(value))
            return null;
        SpannableString spannableString = new SpannableString(value);
        try {
            if (value.contains(".")) {
                spannableString.setSpan(new RelativeSizeSpan(proportion), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return spannableString;
    }

    /**
     * 改变金钱符号跟小数点后面数字的大小
     *
     * @param value
     * @param spValue
     * @return
     */
    @Override
    public SpannableString changDecimalAndMoneySymbolSize(Context context, String value, int spValue) {
        if (TextUtils.isEmpty(value)) {
            return null;
        }
        SpannableString spannableString = null;
        try {
            spannableString = new SpannableString(value);
            if (value.contains(".")) {
                spannableString.setSpan(new AbsoluteSizeSpan(ZljUtils.DIMEN().sp2px(spValue)), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return spannableString;
    }


    /**
     * 改变金钱符号跟小数点后面数字的大小 带后缀
     *
     * @param value
     * @param spValue
     * @return
     */
    @Override
    public SpannableString changDecimalAndMoneySymbolSizeWithSuffix(Context context, String value, int spValue, String suffix, int suffixSpValue) {
        if (TextUtils.isEmpty(value)) {
            return null;
        }
        SpannableString spannableString = null;
        try {

            if (!TextUtils.isEmpty(suffix) && suffixSpValue > 0) {
                value += suffix;
            }

            spannableString = new SpannableString(value);
            if (value.contains(".")) {
                spannableString.setSpan(new AbsoluteSizeSpan(ZljUtils.DIMEN().sp2px(spValue)), value.indexOf("."), value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (!TextUtils.isEmpty(suffix) && suffixSpValue > 0) {
                int start = value.indexOf(suffix);
                spannableString.setSpan(new AbsoluteSizeSpan(ZljUtils.DIMEN().sp2px(suffixSpValue)), start, start + suffix.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return spannableString;
    }


    /**
     * 将字符串转化为double
     */
    @Override
    public double getParseDouble(String amount) {
        double total = 0.0;
        try {
            total = Double.parseDouble(amount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return total;
    }

    @Override
    public int getFontHeight(float fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.bottom - fm.top);
    }

    @Override
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 去掉字符串里面的html代码。<br>
     * 要求数据要规范，比如大于小于号要配套,否则会被集体误杀。
     *
     * @param content 内容
     * @return 去掉后的内容
     */

    @Override
    public String stripHtml(String content) {
        if (content == null) {
            return "";
        }
        try {
            // <p>段落替换为换行
            content = content.replaceAll("<p .*?>", "\r\n");
            // <br><br/>替换为换行
            content = content.replaceAll("<br\\s*/?>", "\r\n");
            // 去掉其它的<>之间的东西
            content = content.replaceAll("\\<.*?>", "");
            // 还原HTML
            // content = HTMLDecoder.decode(content);
            //&ldquo;&quot;&nbsp;
            content = content.replaceAll("&.dquo;", "\"");
            content = content.replaceAll("&nbsp;", " ");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public int getColor(String color, int defaultColor) {
        if (TextUtils.isEmpty(color)) {
            return defaultColor;
        } else {
            if (!color.startsWith("#")) {
                color = "#" + color;
            }
            try {
                return Color.parseColor(color);
            } catch (Exception e) {
                e.printStackTrace();
                return defaultColor;
            }
        }
    }

    /**
     * 正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    @Override
    public String subZeroAndDot(String s) {
        try {
            if (s.indexOf(".") > 0) {
                s = s.replaceAll("0+?$", "");//去掉多余的0
                s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * @param content
     * @return 替换null字段
     */
    @Override
    public String replaceNull(String content) {
        if (content == null) {
            return "";
        }
        return content;
    }

    /**
     * 格式化毫秒数为 xx:xx:xx这样的时间格式。
     *
     * @param ms 毫秒数
     * @return 格式化后的字符串
     */
    @Override
    public String formatMs(long ms) {
        int seconds = (int) (ms / 1000);
        int finalSec = seconds % 60;
        int finalMin = seconds / 60 % 60;
        int finalHour = seconds / 3600;

        StringBuilder msBuilder = new StringBuilder("");
        if (finalHour > 9) {
            msBuilder.append(finalHour).append(":");
        } else if (finalHour > 0) {
            msBuilder.append("0").append(finalHour).append(":");
        }

        if (finalMin > 9) {
            msBuilder.append(finalMin).append(":");
        } else if (finalMin > 0) {
            msBuilder.append("0").append(finalMin).append(":");
        } else {
            msBuilder.append("00").append(":");
        }

        if (finalSec > 9) {
            msBuilder.append(finalSec);
        } else if (finalSec > 0) {
            msBuilder.append("0").append(finalSec);
        } else {
            msBuilder.append("00");
        }

        return msBuilder.toString();
    }

    /**
     * 获取字体宽度
     *
     * @param text
     * @param size
     * @return
     */
    @Override
    public float getTextWidth(String text, float size) {
        if (text == null)
            return 0f;
        Paint paint = new Paint();
        paint.setTextSize(size);
        return paint.measureText(text);
    }

    public final String[] KEYWORDS = {
            "screenshot", "screen_shot", "screen-shot", "screen shot",
            "screencapture", "screen_capture", "screen-capture", "screen capture",
            "screencap", "screen_cap", "screen-cap", "screen cap", "openscreen", "screen_lock", "截屏", "Screenshots"
    };
}
